import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.JBTextArea;
import net.sf.jsqlparser.JSQLParserException;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author laberinto
 * @version 1.0
 * @date 2023/1/31 16:52
 * @package PACKAGE_NAME
 * @message \\TODO
 * (⌓‿⌓)
 */
public class AddNoteDialog extends DialogWrapper {
    /**
     * 标题输入框
     */
    private JTextArea etfTitle;
    private JBTextArea jbTextArea;
    /**
     * 内容输入框
     */
    private JTextArea etfMark;
    /**
     * 注释输入框
     */
    private JTextArea apiMark;

    private Project myProject;
    private PsiFile myPsiFile;
    private Editor myEditor;
    private PsiClass myPsiClass;
    private  List<String> fileList=new ArrayList<>();


    public AddNoteDialog(Project project,PsiFile psiFile,Editor editor,PsiClass psiClass) {
        super(true);
        myProject=project;
        myPsiFile=psiFile;
        myEditor=editor;
        myPsiClass=psiClass;
        setTitle("Sql转换成DTO");

        init();

    }

    @Nullable
    @Override
    protected JComponent createCenterPanel() {
        JPanel panel = new JPanel(new BorderLayout(5,5));
        JLabel jLabel=new JLabel("SQL");
        JLabel jLabel1=new JLabel("DTO");
        JLabel jLabel2=new JLabel("注释");
        etfTitle = new JTextArea();
        Border border = BorderFactory.createLineBorder(Color.gray);
       // etfTitle.setAutoscrolls(true);
        etfTitle.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));
       // etfTitle.setBackground(Color.DARK_GRAY);

        etfMark = new JTextArea();
        etfMark.setAutoscrolls(true);
        etfMark.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));

        apiMark = new JTextArea();
        apiMark.setAutoscrolls(true);
        apiMark.setBorder(BorderFactory.createCompoundBorder(border,BorderFactory.createEmptyBorder(5, 5, 5, 5)));
        //etfMark.setPreferredSize(new Dimension(500,800));
       // etfTitle.setPreferredSize(new Dimension(500,800));

        JPanel jPanel1=new JPanel(new BorderLayout(5,5));
        jPanel1.setPreferredSize(new Dimension(400,800));
        jPanel1.add(jLabel, BorderLayout.NORTH);

        JBScrollPane scrollPane = new JBScrollPane(
                etfTitle,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );

        jPanel1.add(scrollPane, BorderLayout.CENTER);


        JPanel jPanel2=new JPanel(new BorderLayout(5,5));
        jPanel2.setPreferredSize(new Dimension(300,800));
        jPanel2.add(jLabel1, BorderLayout.NORTH);
        JBScrollPane scrollPane2 = new JBScrollPane(
                etfMark,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );
        jPanel2.add(scrollPane2, BorderLayout.CENTER);

        JPanel jPanel3=new JPanel(new BorderLayout(5,5));
        jPanel3.setPreferredSize(new Dimension(100,800));
        jPanel3.add(jLabel2, BorderLayout.NORTH);
        JBScrollPane scrollPane3 = new JBScrollPane(
                apiMark,
                ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );
        jPanel3.add(scrollPane3, BorderLayout.CENTER);


        panel.add(jPanel1, BorderLayout.WEST);
        panel.add(jPanel3,BorderLayout.CENTER);
        panel.add(jPanel2, BorderLayout.EAST);
        return panel;
    }

    @Override
    protected JComponent createSouthPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
        JButton btnAdd = new JButton("立即转换");
        JButton btnCom = new JButton("确认");
        //按钮点击事件处理
        btnAdd.addActionListener(e -> {
            //获取标题
            String name = etfTitle.getText();
            String apiName = apiMark.getText();
            if ("".equals(name)){
                Messages.showMessageDialog(myProject,
                        "请先输入SQL",
                        "提示", Messages.getErrorIcon());
                return;
            }

            try {
                fileList= SqlParserTool.getSelectColumnName(name);
            } catch (JSQLParserException jsqlParserException) {
                jsqlParserException.printStackTrace();
            }
//            String start ="SELECT\n";
//            String end="FROM\n";
//            String s = StringUtils.substringBetween(name, start, end);
//            if (s==null){
//                Messages.showMessageDialog(myProject,
//                        "请输入正确格式的SQL",
//                        "提示", Messages.getErrorIcon());
//                return;
//            }
//            //s=s.replaceAll("\\n","");
//            String[] split = s.split("\n");
            String[] split = apiName.split("\n");
            StringBuffer sb=new StringBuffer();
            int i=0;
            for (String columnName:fileList){
                columnName = CaseUtils.convertToCamelCase(columnName);
                String y ="";

                if (split.length>i){
                     y = "\n@ApiModelProperty(value = \""+split[i]+"\")\n" +
                            "private String " + columnName + ";\n";
                }else {
                    y = "\n@ApiModelProperty(value = \"\")\n" +
                            "private String " + columnName + ";\n";
                }
                sb.append(y);
                i++;
            }

//            for (int i=0;i<split.length;i++){
//                String value="";
//                if (split[i].indexOf("WHEN")!=-1||split[i].indexOf("ELSE")!=-1||split[i].indexOf("OR")!=-1||split[i].indexOf("AND")!=-1){
//
//                }else {
//                    if (split[i].indexOf(" AS ") != -1) {
//                        if (split[i].indexOf(" AS CHAR") != -1) {
//                            if (split[i].split(" AS ").length > 2) {
//                                value = split[i].split(" AS ")[2];
//                                String s1 = CaseUtils.convertToCamelCase(value);
//                                s1 = s1.replaceAll(",", "").trim();
//                                String y = "\n@ApiModelProperty(value = \"\")\n" +
//                                        "private String " + s1 + ";\n";
//                                fileList.add(s1);
//                                sb.append(y);
//                            }
//
//                        } else {
//                            value = split[i].split(" AS ")[1];
//                            String s1 = CaseUtils.convertToCamelCase(value);
//                            s1 = s1.replaceAll(",", "").trim();
//                            String y = "\n@ApiModelProperty(value = \"\")\n" +
//                                    "private String " + s1 + ";\n";
//                            sb.append(y);
//                            fileList.add(s1);
//                        }
//
//                    } else {
//
//                        String[] split1 = split[i].split("\\.");
//                        if (split1.length > 1) {
//                            value = split1[1];
//                            String s1 = CaseUtils.convertToCamelCase(value);
//                            s1 = s1.replaceAll(",", "").trim();
//                            String y = "\n@ApiModelProperty(value = \"\")\n" +
//                                    "private String " + s1 + ";\n";
//                            sb.append(y);
//                            fileList.add(s1);
//                        }
//
//
//                    }
//                }
//            }
            etfMark.setText(sb.toString());




        });
        //按钮点击事件处理
        btnCom.addActionListener(e -> {

            //获取内容
            String content = apiMark.getText();
            String[] split = content.split("\n");
            String className = myPsiClass.getNameIdentifier().getText();
            System.out.println(className);

            WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
                @Override
                public void run() {
                    int i=0;
                    PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(myProject);

                    PsiType psiType = PsiType.getTypeByName("String", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    PsiType psiType2 = PsiType.getTypeByName("Long", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    PsiType psiType3 = PsiType.getTypeByName("BigDecimal", myProject
                            , GlobalSearchScope.EMPTY_SCOPE);
                    for(String file :fileList){
                        PsiField psiField=null;
                        file = CaseUtils.convertToCamelCase(file);
                        if (file.contains("Id")||file.contains("id")){
                             psiField = elementFactory.createField(file, psiType2);
                        }else if (file.contains("Qty")||file.contains("Number")||file.contains("Weight")||file.contains("qty")||file.contains("number")||file.contains("weight")){
                            psiField = elementFactory.createField(file, psiType3);
                        }else {
                            psiField = elementFactory.createField(file, psiType);
                        }


                        PsiModifierList modifierList = psiField.getModifierList();
                        if (modifierList != null) {
                            if (split.length>i){
                               // modifierList.addAnnotation("ApiModelProperty(value = \""+split[i]+"\")");
                                myPsiClass.add(psiField);
                            }else {
                                //modifierList.addAnnotation("ApiModelProperty(value = \"\")");
                                myPsiClass.add(psiField);

                            }
                        }
                    }
                    CodeStyleManager.getInstance(myProject).reformat(myPsiClass);

                }
            });

            WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
                @Override
                public void run() {
                    int i=0;
                    PsiField[] fields = myPsiClass.getFields();
                    for (PsiField psiField:fields){
                        if (split.length>i){
                            String text = psiField.getText();
                            psiField.getModifierList().addAnnotation("ApiModelProperty(value = \""+split[i]+"\")");
                        }else {
                            String text = psiField.getText();
                            psiField.getModifierList().addAnnotation("ApiModelProperty(value = \"\")");
                        }
                        i++;
                    }
                }
            });

            close(0);
        });

        panel.add(btnAdd);
        panel.add(btnCom);
        return panel;
    }



}

